package com.ikingtech.framework.sdk.approve.callback;

import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.core.support.LogHelper;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.framework.sdk.web.annotation.PostRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@Slf4j
@ApiController(value = "/approve/callback", name = "审批中心-审批回调", description = "审批中心-审批回调")
@RequiredArgsConstructor
public class ApproveCallbackResolver {

    private final List<ApproveProcessCallback> callbacks;

    private final Map<String, List<ApproveProcessCallback>> callbackMap = new HashMap<>();

    @PostRequest(order = 1, value = "/resolve", summary = "处理审批回调请求", description = "处理审批回调请求")
    public R<Object> resolve(@RequestBody ApproveCallbackParam param) {
        if (null == param) {
            LogHelper.info("APPROVE CALLBACK RESOLVER", "审批回调参数为空");
            throw new FrameworkException("approveCallbackParamIsBlank");
        }
        if (Tools.Coll.isBlankMap(this.callbackMap)) {
            LogHelper.info("APPROVE CALLBACK RESOLVER", "审批回调处理未实现");
            throw new FrameworkException("approveCallbackNotImplement");
        }
        List<ApproveProcessCallback> businessTypeCallbacks = this.callbackMap.get(param.getBusinessType());
        if (Tools.Coll.isNotBlank(businessTypeCallbacks)) {
            businessTypeCallbacks.forEach(callback -> {
                LogHelper.info("APPROVE CALLBACK RESOLVER", "触发审批回调[{}][{}]", param.getBusinessType(), param);
                callback.invoke(param);
            });
        } else {
            LogHelper.info("APPROVE CALLBACK RESOLVER", "业务类型[{}]未实现回调接口, 执行所有回调", param.getBusinessType());
        }
        this.callbackMap.forEach((businessType, callbacks) -> callbacks.forEach(callback -> {
            LogHelper.info("APPROVE CALLBACK RESOLVER", "触发审批回调[{}][{}]", businessType, param);
            callback.invoke(param);
        }));
        LogHelper.info("APPROVE CALLBACK RESOLVER", "审批回调执行完成");
        return R.ok();
    }

    public void init() {
        this.callbackMap.putAll(Tools.Coll.convertGroup(this.callbacks, ApproveProcessCallback::businessType));
    }
}
